<?php
/**
 * CustomerHelper is functions for handling customers.
 * 
 * ----------------------------------------
 * Bocheng C.           09.08.2013    create new class
 * 
 * LBB Solutions Oy 版权所有 @ 2013
 */
class CustomerHelper {
	const ACTION_EARN_POINT = 'earn.point';
	const ACTION_REDEEM_REWARD = 'redeem.reward';
	const ACTION_REDEEM_OFFER = 'redeem.offer';
	
	/**
	 * Get customer id type: 0 - ID, 1 - Email, 2 - Mobile
	 * @param string $input
	 * @return int 0,1,2
	 */
	static function getType($input) {
		if (false === strpos($input, '@')) {
			//the first char is + or 0
			if (0 === strpos($input, '+') or 0 === strpos($input, '0')) {
				return 2;
			}
			//is length < 8, it should be User ID.
			if (strlen($input) < 8 and (int)$input > 0) return 0;
			elseif ((int)substr($input, -2) > 0 or substr($input, -2) == '00') return 2;//the last 2 chars are int
			else return -1;
		} else {
			return 1;//Email
		}
	}
	
	static function getMobile($text, $hidden = false) {
		if ($hidden) {
			return substr($text, 0, -4) . '****';
		} else return $text;
	}
	static function getEmail($text, $hidden = false) {
		if ($hidden) {
			return substr($text, 0, strpos($text, '@')) . '@****';
		} else return $text;
	}
	
	/**
	 * formatMobile for Finnish number.
	 * @param string $number
	 * @param string $country_code
	 * @return string
	 * @throws Exception
	 */
	static function formatMobile($number, $country_code = 'FI') {
		$formated = str_replace(array('-', ' '), '', $number);
		
		switch ($country_code) {
			case 'FI':
				if (substr($formated, 0, 4) == '+358' and strlen($formated) == 13) return '0' . substr($formated, -9);
				elseif (substr($formated, 0, 3) == '358' and strlen($formated) == 12) return '0' . substr($formated, -9);
				elseif (substr($formated, 0, 1) == '0' and strlen($formated) == 10) return $formated;
				else {
					throw new Exception('This mobile phone number '.$number.' is invalid!');
				}
				break;
			default:
				throw new Exception('SMS service for this number '.$number.' does not support '.$country_code.'!');
		}
	}
	
	private static function _notifyUserWithSMS($phone_number, $message) {
		//only send to FINNISH phone number
		if (substr($phone_number, 0, 1) == '0' and strlen($phone_number) == 10) {
			$phone_number = '+358' . substr($phone_number, -9);
		} else {
			Yii::log("_notifyUserWithSMS : \n"
				. $phone_number . " cannot be reached! \n",
				CLogger::LEVEL_WARNING, 'web.notify.failed');
			return 0;
		}
		
		Yii::import('ext.nexmoPhp.*');
		$sms = new NexmoMessage('368feabd','0d98c734');//this is the key + secret
		$response = $sms->sendText($phone_number, 'Yamii', $message, true);
		if ($response->messages[0]->status == 0) {
			return 1;
		} else {
			Yii::log("_notifyUserWithSMS : \n"
				. '[' . $response->messages[0]->status . '] ' . $response->messages[0]->error-text . "\n"
				. print_r($response, 1) . "\n",
				CLogger::LEVEL_WARNING, 'web.notify.failed');
			return 0;
		}
	}
	
	private static function _notifyUserWithEmail($email, $message, $subject) {
		//send email from admin mail
		$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
		$mailer->IsSMTP();
		$mailer->Host = 'mail.yamii.fi';
		$mailer->Port = '26';
		$mailer->Username = 'admin@yamii.fi';
		$mailer->Password = 'yamii_fi';
		$mailer->SMTPAuth = true;
		$mailer->SetFrom('admin@yamii.fi', 'Yamii.fi');
		$mailer->AddReplyTo('admin@yamii.fi', 'Yamii.fi');
		$mailer->AddAddress($email);
		$mailer->CharSet = 'utf-8';
		$mailer->Subject = $subject;
		$mailer->MsgHTML($message);
		$mailer->Send();
	}
	
	/**
	 * Notify user with app/email/sms.
	 * @param array $targets = array(array('to', 'method', 'message', 'subject'), array('to', 'method', 'message'))
	 */
	public static function notifyUser($targets) {
		if (count($targets) == 0) {
			return;
		}
		
		/*
		//TODO: only send to bocon.chen@gmail.com
		foreach ($targets as $t) {
			if (!empty($t['method']) and !empty($t['to']) and !empty($t['message'])) {
				switch ($t['method']) {
					case 'email':
						if ($t['to'] == 'cbcbear@hotmail.com' or $t['to'] == 'chenluyao612@gmail.com') {
							self::_notifyUserWithEmail($t['to'], $t['message'], $t['title']);
						} else {
							self::_notifyUserWithEmail('bocon.chen@gmail.com', $t['message'], $t['title']);
						}
						break;
					case 'sms':
						if (substr($t['to'], -4) == '7234' or substr($t['to'], -4) == '1616') {
							self::_notifyUserWithSMS($t['to'], $t['message']);
						}
						break;
				}
			}
		}
		return;*/
		
		$current_hour = date('G');
		if ($current_hour > 20 or $current_hour < 7) {
			Yii::log('CustomerHelper::NotifyUser : current hour is ' . $current_hour);
			//return;
		}
		
		foreach ($targets as $t) {
			if (!empty($t['method']) and !empty($t['to']) and !empty($t['message'])) {
				switch ($t['method']) {
					case 'ios':
						$messageData = array(
							'message' => $t['message'],
						);
						//TODO: iOS app need to be implemented. 2013.09.13
						//self::PushNotificationToDevice($t['to'], 'ios', $messageData);
						break;
					case 'android':
						$messageData = array(
							'message' => $t['message'],
						);
						//TODO: Android app need to be implemented. 2013.09.13
						//self::PushNotificationToDevice($t['to'], 'android', $messageData);
						break;
					case 'email':
						self::_notifyUserWithEmail($t['to'], $t['message'], $t['title']);
						break;
					case 'sms':
						try {
							$phone = self::formatMobile($t['to']);
							self::_notifyUserWithSMS($phone, $t['message']);
						} catch (Exception $ex) {
							Yii::log("CustomerHelper::notifyUser : \n"
								. $ex->getCode() . " : " . $ex->getMessage() . "\n"
								. $ex->getTraceAsString() . "\n",
								CLogger::LEVEL_ERROR, 'web.notify.failed');
						}
						break;
					default:
						//TODO: logging
						Yii::log('CustomerHelper::notifyUser : do not support notifing method' . $t['method']
							."\n" . print_r($t, 1), CLogger::LEVEL_WARNING);
						break;
				}
			}
		}
	}
}